package org.yray.netty.udp;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

@Slf4j
@Service
public class SipServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    private Channel channel;





    public Channel getChannel() {
        return channel;
    }

    public void setChannel(Channel channel) {
        this.channel = channel;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //关闭之后会导致netty不可用，udp是单通道的 尽量防止异常抛到这里
        ctx.close();
        log.error(cause.getMessage(), cause);
    }

    //发送udp数据包 注意gbk编码
    public void send(String msg, InetSocketAddress sender) {
        ByteBuf byteBuf = Unpooled.copiedBuffer(msg.getBytes());
        channel.writeAndFlush(new DatagramPacket(byteBuf, sender));
        //log.debug("send to {},{}", sender.getAddress().getHostAddress(), sender.getPort());
        log.info("----send----{}:{}----------------------------------------",sender.getAddress().getHostAddress(),sender.getPort());
        log.info("sipMsg={}", msg);
    }

    public void sendToSipServer(String msg)
    {
        while (true) {
            if(channel==null||!channel.isActive())
            {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            else {
                send(msg,new InetSocketAddress ("121.13.226.156",5061));
                break;
            }

        }

    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, DatagramPacket packet) throws Exception {
        {
            //去除空包，公网状态下很多空包 应该是服务器端口被探测
            InetSocketAddress sender = packet.sender();
            log.info(" ----receive----{}:{}---------------------------------------------",sender.getAddress().getHostAddress(), sender.getPort());
            if (packet.content().readableBytes() < 1) {
                return;
            }
            byte[] data = new byte[packet.content().readableBytes()];
            packet.content().readBytes(data);
            try {
                log.info("sipMsg={}", new String(data));

            } catch (Exception e) {
                log.error("Exception:{}", e);
                //throw e;
            }

        }

    }
}

